package com.eightbears.beboy.ui.user.fragment;


import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.WaitPaymentAdapter;
import com.eightbears.beboy.base.BaseFragment;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.entity.WaitPaymentEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.beboy.ui.user.activity.OrderDetailActivity;
import com.eightbears.beboy.ui.user.activity.PaymentActivity;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.URL_PAYMENT_ORDERS;
import static com.eightbears.beboy.base.util.CommonAPI.delayMillis;
import static com.eightbears.beboy.base.util.GsonUtil.fromJson;
import static com.eightbears.beboy.entity.WaitPaymentEntity.PARAMS_WAIT_PAYMENT;
import static com.eightbears.beboy.ui.user.activity.OrderDetailActivity.EVENT_CANCEL_ORDER;

public class WaitPaymentOrderFragment extends BaseFragment  implements
        BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener{

    @BindView(R.id.rv_list)
    RecyclerView rv_list;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.view_empty)
    View view_empty;
    private WaitPaymentAdapter mWaitPaymentAdapter;
    private  WaitPaymentEntity.WaitPayment waitPayment;
    private int page = 1;
    private boolean isErr = true;
    private int isEnd = 1;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_wait_payment_order_fragmet, container, false);
        ButterKnife.bind(this, view);
        initView();
        initData();
        initEvent();
        return view;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        initAdapter();
    }

    @Override
    protected void initData() {
        getData();
    }

    @Override
    protected void initEvent() {
        mWaitPaymentAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                waitPayment = (WaitPaymentEntity.WaitPayment) adapter.getData().get(position);
                switch (view.getId()){
                    case R.id.tv_shopbook_mealbug:
                        startLocalActivity(PaymentActivity.class, PARAMS_WAIT_PAYMENT, waitPayment);
                        break;
                    case R.id.shop_info_meal:
                        startLocalActivity(OrderDetailActivity.class, PARAMS_WAIT_PAYMENT, waitPayment);
                        break;
                }
            }
        });
    }

    private void initAdapter() {
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setColorSchemeColors(getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color));
        rv_list.setLayoutManager(new LinearLayoutManager(getActivity()));
        mWaitPaymentAdapter = new WaitPaymentAdapter();
        mWaitPaymentAdapter.openLoadAnimation();
        mWaitPaymentAdapter.setOnLoadMoreListener(this);
        rv_list.setAdapter(mWaitPaymentAdapter);
    }

    private void getData() {
        swipeLayout.setRefreshing(true);
        OkHttpUtils.get().url(URL_PAYMENT_ORDERS)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("page", String.valueOf(page))
                .addParams("size", "1000")
                .addParams("status", "0")
                .addParams("type", "4")
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                swipeLayout.setRefreshing(false);
                WaitPaymentEntity waitPaymentEntity = fromJson(response, WaitPaymentEntity.class);
                if(waitPaymentEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)){
                    if(page == 1){
                        if(waitPaymentEntity.getData().getList().size() == 0) {
                            view_empty.setVisibility(View.VISIBLE);
                            rv_list.setVisibility(View.GONE);
                        } else {
                            view_empty.setVisibility(View.GONE);
                            rv_list.setVisibility(View.VISIBLE);
                            mWaitPaymentAdapter.setNewData(waitPaymentEntity.getData().getList());
                        }

                    }
                    else {
                        mWaitPaymentAdapter.addData(waitPaymentEntity.getData().getList());
                    }
                    mWaitPaymentAdapter.loadMoreComplete();
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
                swipeLayout.setRefreshing(false);
                isErr = false;
                Status_Error status_error = fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(getActivity(), status_error);
            }
        });
    }

    @Override
    public void onRefresh() {
        mWaitPaymentAdapter.setEnableLoadMore(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isErr = true;
                page = 1;
                mWaitPaymentAdapter.getData().clear();
                mWaitPaymentAdapter.notifyDataSetChanged();
                getData();
            }
        }, delayMillis);
    }

    @Override
    public void onLoadMoreRequested() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isEnd == 1) {
                    mWaitPaymentAdapter.loadMoreEnd(true);
                } else {
                    if (isErr) {
                        page++;
                        getData();
                    } else {
                        isErr = true;
                        Toast.makeText(getActivity(), R.string.network_anomalies, Toast.LENGTH_LONG).show();
                        mWaitPaymentAdapter.loadMoreFail();
                    }
                }
            }
        }, delayMillis);
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onDataSynEvent(String event) {
        switch (event) {
            case EVENT_CANCEL_ORDER:
                mWaitPaymentAdapter.getData().remove(waitPayment);
                mWaitPaymentAdapter.notifyDataSetChanged();
                if(mWaitPaymentAdapter.getData().size() == 0) {
                    view_empty.setVisibility(View.VISIBLE);
                    rv_list.setVisibility(View.GONE);
                }
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
